import React from "react";
import { Select, Space } from 'antd';
import { apiGetEventStatisticsOverview, apiGetEventStatisticsTrend } from '@/request/dataBoard'
import './style/style.less'
import '@/font/iconfont.css'
import Card from "@/views/dataBoard/components/card.jsx"
import OnlineIncome from '@/views/dataBoard/components/IsOnlineIncomenew.jsx'
import _ from 'lodash'
import moment from 'moment';
import TheButton from "@/components/TheButton";
import Json2Excel from '@/utils/Json2Excel';

class Index extends React.Component {
  state = {
    dataSource: [],
    chartData: {
      eventTrendList: [],
      dateList: []
    },
    selectVal: "onlineMall",
    onlineName: "dataBoardNowData",
    time: ""
  }

  async componentDidMount() {
    await this.getData();
    await this.getChartData();
    // this.setState({
    //     time: moment(new Date(new Date().getTime() - 24 * 60 * 60 * 1000)).format('YYYY-MM-DD') + "~" + moment(new Date()).format('YYYY-MM-DD'),
    // })
  }


  getData = async () => {
    let res = await apiGetEventStatisticsOverview({ "dateType": "current", "businessType": this.state.selectVal, })
    let UnitDispose = (data) => {
      if (!!data) {
        if (Number(data) > 1000000) {
          return Number(data) > 1000000 ? (Number(data) / 1000000).toFixed(2) + "百万" : Number(data)
        } else {
          return (Number(data) > 10000 ? (Number(data) / 10000).toFixed(2) + "万" : Number(data) || 0)
        }
      } else {
        return 0
      }
    };
    if (res.data && res.code === 0) {
      let data = res.data
      let dataSource = [];
      if (this.state.selectVal === "pet") {
        dataSource = [
          {
            top:
            {
              title: '访客人数',
              value: UnitDispose(data.storeVisitorCount),
              explain: "统计范围：统计周期内浏览任意页面 / 商城TAB及相关页面 / 宠圈TAB及相关页面 / 门店到店自提和洗护美容相关页面的去重人数。去重逻辑：账户在统计时间范围内访问多次只记为一个。注：不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.storeVisitorCountTrend,
            },
          },
          {
            top:
            {
              title: '查看帖子详情人数',
              value: UnitDispose(data.dynamicViewCount),
              explain: "统计范围：统计周期内用户点击进入帖子详情页浏览的人数去重逻辑：账户在统计时间范围内访问多次只记为一个。注：不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.dynamicViewCountTrend
            }
          },
          {
            top:
            {
              title: '人均查看帖子数',
              value: UnitDispose(data.dynamicSingleViewCount),
              explain: "贴子数/访客数",
              yesterday: data.dynamicSingleViewCountTrend
            }
          },
          {
            top:
            {
              title: '发帖人数',
              value: UnitDispose(data.dynamicCreateCount),
              explain: "统计范围：统计周期内用户发布帖子（不考虑审核是否通过）的人数去重逻辑：根据账号去重，不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.dynamicCreateCountTrend
            }
          },
          {
            top:
            {
              title: '点赞人数',
              value: UnitDispose(data.dynamicLikeCount),
              explain: "统计范围：统计周期内用户对帖子点赞的人数；去重逻辑：根据账号去重，不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.dynamicLikeCountTrend
            }
          },
          {
            top:
            {
              title: '分享人数',
              value: UnitDispose(data.dynamicShareCount),
              explain: "统计范围：统计周期内用户对帖子分享的人数去重逻辑：根据账号去重，不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.dynamicShareCountTrend
            }
          },
          {
            top:
            {
              title: '评论人数',
              value: UnitDispose(data.dynamicCommentCount),
              explain: "统计范围：统计周期内用户对帖评论的人数去重逻辑：根据账号去重，不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.dynamicCommentCountTrend
            }
          },
          {
            top:
            {
              title: '平均停留时长(分钟)',
              value: UnitDispose(data.stayDuration ? (data.stayDuration / 60).toFixed(1) : 0),
              explain: "停留总时长/访客人数 停留总时长：统计周期内打开相关页面到退出的浏览时长之和",
              yesterday: data.stayDurationTrend
            }
          },
        ]
      } else if (this.state.selectVal.includes('mhc')) {
        dataSource = [
          {
            top:
            {
              title: '服务选择页访客数',
              value: UnitDispose(data.visitorCount),
              explain: "当日浏览上门服务选择页的人数（根据用户id去重）",
              nowData: true,
              yesterday: data.visitorCountTrend,
            },
          },
          {
            top:
            {
              title: '提单页访客数',
              value: UnitDispose(data.orderVisitorCount),
              explain: "当日浏览提单页的访客人数（根据用户id去重）",
              nowData: true,
              yesterday: data.orderVisitorCountTrend
            }
          },
          {
            top:
            {
              title: '预约-提单页转化率',
              value: data.orderVisitorRatio ? UnitDispose(((Number(data.orderVisitorRatio) * 100)).toFixed(2)) + "%" : 0,
              explain: "预约-提单页转化率= 提单页访客数 / 服务选择页访客数 *100%",
              nowData: true,
              yesterday: data.orderVisitorRatioTrend
            }
          },
          {
            top:
            {
              title: '支付人数',
              value: UnitDispose(data.storePayCount),
              explain: "当日上门服务订单的支付人数之和（根据用户id去重）",
              nowData: true,
              yesterday: data.storePayCountTrend
            }
          },
          {
            top:
            {
              title: '访客支付转化率',
              value: data.storePayRatio ? UnitDispose(((Number(data.storePayRatio) * 100)).toFixed(2)) + "%" : 0,
              explain: "访客支付转化率=支付人数 / 服务选择页访客数 * 100%",
              nowData: true,
              yesterday: data.storePayRatioTrend
            }
          },
          {
            top:
            {
              title: '支付订单数',
              value: UnitDispose(data.storeOrderCount),
              explain: "下单时间在当日，且已支付的订单的数量之和（注：单个用户一次性下单多次喂养 或 多只洗护，则统计为多笔订单）",
              nowData: true,
              yesterday: data.storeOrderCountTrend
            }
          },
          {
            top:
            {
              title: '支付金额',
              value: data.storePayPrice ? UnitDispose(((Number(data.storePayPrice) / 100)).toFixed(2)) : 0,
              explain: "当日支付订单的实付金额之和",
              nowData: true,
              yesterday: data.storePayPriceTrend
            }
          },
          {
            top:
            {
              title: '客单价',
              value: data.storePaySinglePrice ? UnitDispose(((Number(data.storePaySinglePrice) / 100)).toFixed(2)) : 0,
              explain: "客单价=支付金额 / 支付人数",
              nowData: true,
              yesterday: data.storePaySinglePriceTrend
            }
          },
          {
            top:
            {
              title: '退款订单数',
              value: data.refundCount,
              explain: "退款成功时间在当日的订单数量之和（注：单个用户一次性退款成功多次喂养 或 多只洗护，则统计为多笔订单）",
              nowData: true,
              yesterday: data.refundCountTrend
            }
          },
          {
            top:
            {
              title: '退款金额',
              value: data.refundPrice ? UnitDispose(((Number(data.refundPrice) / 100)).toFixed(2)) : 0,
              explain: "当日退款成功的订单的实退金额之和，包括由于变更而导致的退款金额",
              nowData: true,
              yesterday: data.refundPriceTrend
            }
          },
        ]
      } else {
        dataSource = [
          {
            top:
            {
              title: '访客人数',
              value: UnitDispose(data.storeVisitorCount),
              explain: "统计范围：统计周期内浏览任意页面 / 商城TAB及相关页面 / 宠圈TAB及相关页面 / 门店到店自提和洗护美容相关页面的去重人数。去重逻辑：账户在统计时间范围内访问多次只记为一个。注：不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.storeVisitorCountTrend
            },
          },
          {
            top:
            {
              title: '加购人数',
              value: UnitDispose(data.storeCartCount),
              explain: "统计范围：统计周期内在对应页面 （商城TAB及相关页面 / 宠圈TAB及相关页面 / 门店到店自提和洗护美容）有加购商品动作的去重人数。去重逻辑：账户在统计时间范围内访问多次只记为一个。注：不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.storeCartCountTrend
            }
          },
          {
            top:
            {
              title: '访客加购率',
              value: data.storeCartRatio ? UnitDispose(((Number(data.storeCartRatio) * 100)).toFixed(2)) + "%" : 0,
              explain: "加购人数/访客人数",
              yesterday: data.storeCartRatioTrend
            }
          },
          {
            top:
            {
              title: '支付人数',
              value: UnitDispose(data.storePayCount),
              explain: "未剔除事后退款的人数（退款包括售中和售后的仅退款和退货退款）去重逻辑：账户在统计时间范围内支付多笔订单多次只记为一个。注：不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.storePayCountTrend
            }
          },
          {
            top:
            {
              title: '访客支付转化率',
              value: data.storePayRatio ? UnitDispose(((Number(data.storePayRatio) * 100)).toFixed(2)) + "%" : 0,
              explain: "支付人数/访客人数",
              yesterday: data.storePayRatioTrend
            }
          },
          {
            top:
            {
              title: '支付订单数',
              value: UnitDispose(data.storeOrderCount),
              explain: "未剔除事后退款订单（退款包括售中和售后的仅退款和退货退款）",
              yesterday: data.storeOrderCountTrend
            }
          },
          {
            top:
            {
              title: '支付金额',
              value: data.storePayPrice ? UnitDispose(((Number(data.storePayPrice) / 100)).toFixed(2)) : 0,
              explain: "未剔除事后退款金额（退款包括售中和售后的仅退款和退货退款）",
              yesterday: data.storePayPriceTrend
            }
          },
          {
            top:
            {
              title: '客单价',
              value: data.storePaySinglePrice ? UnitDispose(((Number(data.storePaySinglePrice) / 100)).toFixed(2)) : 0,
              explain: "支付金额数/支付人数",
              yesterday: data.storePaySinglePriceTrend
            }
          },
          {
            top:
            {
              title: '平均停留时长(分钟)',
              value: UnitDispose(data.stayDuration ? (data.stayDuration / 60).toFixed(1) : 0),
              explain: "停留总时长/访客人数 停留总时长：统计周期内打开相关页面到退出的浏览时长之和",
              yesterday: data.stayDurationTrend
            }
          },
          {
            top:
            {
              title: '退款订单数',
              value: UnitDispose(data.refundCount),
              explain: "在时间范围内申请退款并退款成功的订单数",
              nowData: true,

              yesterday: data.refundCountTrend
            }
          },
          {
            top:
            {
              title: '退款金额',
              value: data.refundPrice ? UnitDispose(((Number(data.refundPrice) / 100)).toFixed(2)) : 0,
              explain: "在时间范围内申请退款并退款成功订单的退款金额之和",
              nowData: true,

              yesterday: data.refundPriceTrend
            }
          },
          // {
          //     top:
          //     {
          //         title: '退款金额同比趋势',
          //         value: data.refundPriceTrend ? ((Number(data.refundPriceTrend) * 100)) + "%" : "0%",
          //         explain: "",
          //         yesterday: data.storePayRatioTrend
          //     }
          // },
          // {
          //     top:
          //     {
          //         title: '退款订单数量同比趋势',
          //         value: data.refundCountTrend ? ((Number(data.refundCountTrend) * 100)) + "%" : "0%",
          //         explain: "",
          //         yesterday: data.storePayRatioTrend
          //     }
          // },
        ]
      }
      this.setState({ dataSource, time: (res.data.endTime ? res.data.endTime : "未知") })
    }
  }
  getChartData = async () => {
    let res = await apiGetEventStatisticsTrend({ "dateType": "current", "businessType": this.state.selectVal, })
    if (res.data && res.code === 0) {
      let data = res.data
      this.setState({
        chartData: {}
      }, () => {
        this.setState({
          chartData: data
        })
      })

    }
  }


  handleChange = async (value) => {

    const onlineName = value.includes('mhc') ? 'mhc' : 'dataBoardNowData'
    this.setState({
      selectVal: value,
      onlineName
    }, () => {
      this.getData();
      this.getChartData()
    })


  };
  OnlineIncomes = React.createRef()

  toExprot = () => {
    const { dataSource, selectVal, time } = this.state
    this.setState({
      exportLoading: true
    })
    let label = ""
    switch (selectVal) {
      case "mhcAll":
        label = "上门服务-全部"
        break;
      case "mhcFeed":
        label = "上门服务-喂养"
        break;
      case "mhcCare":
        label = "上门服务-洗护"
        break;
      case "onlineMall":
        label = "线上商城"
        break;
      case "pet":
        label = "宠圈"
        break;
      case "store":
        label = "门店"
        break;
      default:
        break;
    }
    dataSource.map((item, index) => {
      if (item.top.yesterday > 0) {
        item.trend = "上升"
      } else if (item.top.yesterday < 0) {
        item.trend = "下降"
      } else {
        item.trend = "-"
      }
      item.title = item.top.title
      item.value = item.top.value
      item.yesterday = (item.top.yesterday * 100).toFixed(2) + "%"
    })
    const option = {
      header: [
        {
          title: '业务范围：' + label + "\r\n" + "统计时间：" + time,
          prop: '',
          children: [
            { prop: 'title', title: '数据名称' },
            { prop: 'value', title: '数据值', valueType: 'n' },
            { prop: 'trend', title: '环比趋势' },
            { prop: 'yesterday', title: '环比幅度', valueType: 'n' }
          ]
        }
      ],
      fileName: "概览数据",
      dataSource,
    }
    this.setState({
      exportLoading: false
    })
    Json2Excel(option);
  }

  render() {
    const { dataSource, chartData, onlineName } = this.state
    return <div className={"p-layout-box configuration"}>
      <p className="realTitle">实时总览</p>
      <div className="realTime" >
        <div>
          业务范围：
          <Select
            defaultValue="onlineMall"
            style={{
              width: 200,
            }}
            onChange={this.handleChange}
            options={[
              {
                value: 'mhcAll',
                label: '上门服务-全部',
              },
              {
                value: 'mhcFeed',
                label: '上门服务-喂养',
              },
              {
                value: 'mhcCare',
                label: '上门服务-洗护',
              },
              {
                value: 'onlineMall',
                label: '线上商城',
              },
              {
                value: 'pet',
                label: '宠圈',
              },
              {
                value: 'store',
                label: '门店',
              },
            ]}
          />

        </div>
        <div>
          更新时间：{this.state.time}
        </div>
        <div>
          <TheButton haspermi={["dataBoard:nowData:export"]} type="primary" size="middle" onClick={this.toExprot}>导出</TheButton>
        </div>
      </div>
      <div className="card-box">
        {
          dataSource.map((v, i) => {
            return <Card key={i} top={v.top} nowData={v.top.nowData} />
          })
        }
      </div>
      <div style={{ marginTop: 30, fontWeight: 700, fontSize: 22 }}>实时累积趋势</div>

      <OnlineIncome data={chartData} name={onlineName} style={{ overflow: 'auto' }} height={'500px'} width={'100%'} />
    </div>
  }
}

export default Index;
